package com.star.niuke;

/**
 * @author: liminghui
 * @date: 2021/7/26 11:14
 * @version: 1.0
 * @description: 二分法查找
 */
public class SearchTwo {

    public static void main(String[] args) {
        SearchTwo searchTwo = new SearchTwo();
        int[] nums = {1, 2, 4, 4, 5};
        int target = 4;
        int searchIdx = searchTwo.search(nums, target);
        System.out.println("searchIdx=" + searchIdx);
    }

    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0)
            return -1;
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                //找到之后，往左边找
                while (mid != 0 && nums[mid] == nums[mid - 1])
                    mid--;
                return mid;
            }
        }
        return -1;
    }
}
